package com.gxyk.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.widget.Toast;

public class ImageUtil {

	/**
	 * 根据名字获取drawable资源id
	 * 
	 * @param context
	 * @param name
	 *            drawable资源名字
	 * @return
	 */
	public static int getIdentifier(Context context, String name) {
		if (TextUtils.isEmpty(name)) {
			return 0;
		}
		int id = context.getResources().getIdentifier(name, "drawable",
				context.getPackageName());
		return id;
	}

	/**
	 * 根据drawable资源名字获取资源图片的高度
	 * 
	 * @param context
	 * @param drawable资源名字
	 * @return
	 */
	public static int getBitmapHeight(Context context, String drawable) {
		try {
			int id = getIdentifier(context, drawable);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeResource(context.getResources(), id, options);
			return options.outHeight;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 * 根据文件路径获取一张预览效果图(提供默认大小的method，minSideLength=-1，maxNumOfPixels=128*128)
	 * 
	 * @param context
	 *            上下文
	 * @param inPath
	 *            路径
	 * @return Bitmap
	 */
	public static Bitmap getThumbimgByPath(Context context, String inPath) {
		return getThumbimgByPath(context, inPath, -1, 512 * 512);
	}

	/**
	 * 根据文件路径获取一张预览效果图
	 * 
	 * @param context
	 *            上下文
	 * @param inPath
	 *            路径
	 * @param minSideLength
	 *            支持的最小长度
	 * @param maxNumOfPixels
	 *            最大的像素(比如:128*128,200*200等)
	 * @return Bitmap
	 */
	public static Bitmap getThumbimgByPath(Context context, String inPath,
			int minSideLength, int maxNumOfPixels) {
		if (TextUtils.isEmpty(inPath)) {
			Toast.makeText(context, "文件不存在,请检查后重试!", Toast.LENGTH_SHORT).show();
			return null;
		}
		File file = new File(inPath);
		if (!file.exists()) {
			Toast.makeText(context, "文件不存在,请检查后重试!", Toast.LENGTH_SHORT).show();
			return null;
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(inPath, options);
		options.inSampleSize = computeSampleSize(options, minSideLength,
				maxNumOfPixels);
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(inPath, options);
		return bitmap;
	}

	/**
	 * 计算图片采样值
	 * 
	 * @param options
	 *            BitmapFactory.Options
	 * @param minSideLength
	 *            支持的最小长度
	 * @param maxNumOfPixels
	 *            最大的像素(比如:128*128,200*200等)
	 * @return
	 */
	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength,
				maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}
		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	/**
	 * Check the SD card
	 * 
	 * @return
	 */
	public static boolean checkSDCardAvailable() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}

	/**
	 * Save image to the SD card
	 * 
	 * @param photoBitmap
	 * @param photoName
	 * @param path
	 */
	public static void savePhotoToSDCard(Bitmap photoBitmap, String path,
			String photoName) {
		if (checkSDCardAvailable()) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			File photoFile = new File(path, photoName + ".jpg");
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
							fileOutputStream)) {
						fileOutputStream.flush();
						// fileOutputStream.close();
					}
				}
			} catch (FileNotFoundException e) {
				photoFile.delete();
				e.printStackTrace();
			} catch (IOException e) {
				photoFile.delete();
				e.printStackTrace();
			} finally {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Try to return the absolute file path from the given Uri
	 * 
	 * @param context
	 * @param uri
	 * @return the file path or null
	 */
	public static String getRealFilePath(final Activity context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String path = null;
		if (scheme == null)
			path = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			path = uri.getPath();
			if (path != null && path.endsWith(".gif")) {
				// Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
	//			EvmUtil.selPictureFromAlbum(context);
				return null;
			}
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				cursor.moveToFirst();
				path = cursor.getString(cursor
						.getColumnIndex(ImageColumns.DATA));
				cursor.close();
				if (path != null && path.endsWith(".gif")) {
					// Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
		//			EvmUtil.selPictureFromAlbum(context);
					return null;
				}
			}
		}
		return path;
	}

	/**
	 * 将图片转换成圆形
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getHeight(), bitmap.getWidth());
		final RectF rectF = new RectF(rect);
		// final float roundPx = bitmap.getWidth() /1;
		final float roundPx = bitmap.getWidth() / 2;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 转换图片成圆形
	 * 
	 * @param bitmap
	 *            传入Bitmap对象
	 * @return
	 */
	public static Bitmap toRoundBitmap(Bitmap bitmap) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float roundPx;
		float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
		if (width <= height) {
			roundPx = width / 2;
			top = 0;
			bottom = width;
			left = 0;
			right = width;
			height = width;
			dst_left = 0;
			dst_top = 0;
			dst_right = width;
			dst_bottom = width;
		} else {
			roundPx = height / 2;
			float clip = (width - height) / 2;
			left = clip;
			right = width - clip;
			top = 0;
			bottom = height;
			width = height;
			dst_left = 0;
			dst_top = 0;
			dst_right = height;
			dst_bottom = height;
		}
		Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect src = new Rect((int) left, (int) top, (int) right,
				(int) bottom);
		final Rect dst = new Rect((int) dst_left, (int) dst_top,
				(int) dst_right, (int) dst_bottom);
		final RectF rectF = new RectF(dst);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, src, dst, paint);
		return output;
	}
}
